package com.example.mytestdemo.linearlayoutmanager

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mytestdemo.BaseViewBindActivity
import com.example.mytestdemo.R
import com.example.mytestdemo.databinding.ActivityCustomlinearScaleLayoutBinding

/**
 *
 * 中间大两边小
 */
class LinearLayoutScaleActivity : BaseViewBindActivity<ActivityCustomlinearScaleLayoutBinding>() {
    override fun getLayoutInflateId(): Int {
        return R.layout.activity_customlinear_scale_layout
    }

    override fun initData() {
        mBind.recycleview.layoutManager = CustomScaleLayoutManager(this)

        val data = listOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5","Item 6", "Item 2", "Item 3", "Item 4", "Item 50")

        val adapter = CustomLinearScaleAdapter(data)
        mBind.recycleview.adapter = adapter
    }

    override fun initUI() {
    }

}




class CustomScaleLayoutManager(context: Context) : LinearLayoutManager(context, VERTICAL, false) {

    override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
        super.onLayoutChildren(recycler, state)
        scaleDownItems()
    }

    override fun scrollVerticallyBy(
        dy: Int,
        recycler: RecyclerView.Recycler?,
        state: RecyclerView.State?
    ): Int {
        scaleDownItems()
        return super.scrollVerticallyBy(dy, recycler, state)
    }
    private fun scaleDownItems() {
        val mid = height / 2.0f
        for (i in 0 until childCount) {
            val child = getChildAt(i)!!
            val childMid = (getDecoratedTop(child) + getDecoratedBottom(child)) / 2.0f
            val scale = 1 - Math.abs(mid - childMid) / mid * 0.5f
            child.scaleX = scale
            child.scaleY = scale
        }
    }
}




class CustomLinearScaleAdapter(private val dataList: List<String>) :
    RecyclerView.Adapter<CustomLinearScaleAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.custom_layout_scale_item_layout, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(dataList[position])
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val textView: TextView = itemView.findViewById(R.id.textView)

        fun bind(text: String) {
            textView.text = text
        }
    }
}
